package com.stanwind.dbselector.aop;

import java.util.HashMap;
import java.util.Optional;

/**
 * NodeHolder 存储hint
 *
 * @author : stan
 * @version : 1.0
 * @date :  2022/8/19 4:23 PM
 **/
public class NodeContext {
    private final static ThreadLocal<NodeContext> localContext = new ThreadLocal<>();
    private final HashMap<String, Object> values = new HashMap<>();
    public static final String KEY_PARAMS = "HINT_KEY";
    public static NodeContext getContext() {
        NodeContext context =  localContext.get();
        if (context == null) {
            context = new NodeContext();
            localContext.set(context);
        }

        return context;
    }

    public void clear() {
        NodeContext context = localContext.get();
        if (context != null) {
            context.values.clear();
        }

        context = null;
    }


    public void addObject(String key, Object value) {
        values.put(key, value);
    }

    protected Object getObject(String key) {
        return values.get(key);
    }

    public <T> T getObject(String key, Class<T> clz) {
        return clz.cast(values.get(key));
    }
    public <T> T getObjectOrDefault(String key, T def, Class<T> clz) {
        return Optional.ofNullable(getObject(key,clz)).orElse(def);
    }

    public void removeObject(String key) {
        values.remove(key);
    }

    public String getHint() {
        return getObjectOrDefault(KEY_PARAMS, null, String.class);
    }

    public void putHint(String hint) {
        addObject(KEY_PARAMS, hint);
    }
}
